<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\notice;

use app\command\BaseWork;
use app\service\notice\NoticeProducerService;
use think\console\Input;
use think\console\Output;

/*
 * 提醒入队列
 */

class NoticeProduceWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('notice_produce_work');
        // 设置参数
        $this->setDescription('生成发送提醒队列生产')
            ->setHelp('php think notice_produce_work');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $this->getOutputMessage('生成发送提醒队列开始');
        $obj = new NoticeProducerService();
        // 超过5min就停止
        $t = time();
        $runTime = 5 * 60;
        $page = 1;
        while (time() - $t <= $runTime) {
            $items = $obj->getWaitList($page++);
            if (! count($items)) {
                $this->getOutputMessage('暂无数据');
                sleep(rand(5, 10));
                $page = 1;
            }
            if ($page > 100) {
                $page = 1;
            }
            foreach ($items as $model) {
                try {
                    $id = strval($model->getAttr('_id'));
                    $this->getOutputMessage('添加[' . $id . ']任务开始');
                    if (! $obj->runTask($model)) {
                        $this->getOutputMessage('添加[' . $id . ']任务添加失败');
                    }
                    $this->getOutputMessage('添加[' . $id . ']任务结束');
                } catch (\Exception $e) {
                    $this->getOutputMessage('错误：' . $e->getMessage());
                    echo $e->getLine() . PHP_EOL;
                    echo $e->getFile() . PHP_EOL;
                    echo $e->getTraceAsString() . PHP_EOL;
                }
            }
        }
        $this->getOutputMessage('生成发送提醒队列结束');
    }
}
